import React, { useState, useEffect } from "react";
import {
  Col,
  Button,
  Row,
  Radio,
  Form,
  Select,
  message,
  InputNumber,
  Spin
} from "antd";
import queryString from "query-string";
import { quotaList, addQuota } from "../../services/quotaApi";
import styles from "./add.less";
import FixedBottomWrapper from "../../../../components/FixedBottomWrapper";
import SMSpackageList from "../components/SMSpackageList";
import MinusInputAdd from "../components/MinusInputAdd";

function floatThousandUnitValue(value) {
  if (value) {
    return parseFloat((value * 1000).toFixed(0));
  }
  return 0;
}

const formDefaultLayout = {
  labelCol: { span: 3 },
  wrapperCol: { span: 10 },
  labelAlign: "left"
};

const YEAR = 1;
const MONTH = 2;

const FIXED_PACKAGE = 1;
const CUSTOM_PACKAGE = 2;

const EFFECT_RIGHT_NOW = 1;
const EFFECT_NEXT_TIME = 2;

const columns = [
  {
    title: "消息源名称",
    dataKey: "msgSourceName"
  },
  {
    title: "渠道名称",
    dataKey: "pushChannelName"
  },
  {
    title: "归属部门",
    dataKey: "ownerDeptName"
  },
  {
    title: "管理员",
    dataKey: "owner",
    func: val =>
      val
        ? JSON.parse(val)
            .map(item => item.name)
            .join(",")
        : ""
  },
  {
    title: "审批状态",
    dataKey: "auditStatus",
    func: val =>
      ({
        "0": "待审批",
        "1": "已发布",
        "-1": "未通过",
        "2": "未发布"
      }[String(val)])
  },
  {
    title: "创建时间",
    dataKey: "createTime"
  },
  {
    title: "当前使用配额",
    dataKey: "usedQuota",
    func: text => (text || text === 0 ? `${text}条` : "-")
  },
  {
    title: "当月使用配额",
    dataKey: "monthUsedQuota",
    func: text => (text || text === 0 ? `${text}条` : "-")
  },
  {
    title: "当前续订总额",
    dataKey: "renewQuota",
    func: text => (text || text === 0 ? `${text}条` : "-")
  },
  {
    title: "当月续订总额",
    dataKey: "monthRenewQuota",
    func: text => (text || text === 0 ? `${text}条` : "-")
  }
];

const group = Math.ceil(columns.length / 2);

const rows = [];
for (let i = 0; i < group; i += 1) {
  const arr = columns.slice(i * 2, i * 2 + 2);
  rows.push(arr);
}

function Add(props) {
  const { location, history } = props;
  const {
    getFieldDecorator,
    setFieldsValue,
    validateFieldsAndScroll,
    getFieldValue
  } = props.form;
  const { msgSourceId, effectiveStatus } = queryString.parse(location.search);

  const [disabledFields, updateDisabledFields] = useState({
    monitorMarginQuota: true,
    renewMarginQuota: true,
    renewQuotaThousand: true
  });
  const [initialData, updateInitalData] = useState({});
  const [curData, updateCurData] = useState({});
  const [loading, updateLoading] = useState(false);

  const [syncPackageType, updateSyncPackageType] = useState();
  const [syncQuotaType, updateSyncQuotaType] = useState();

  const [quotaValue, updateQuotaValue] = useState();

  // 请求
  const fetchList = async () => {
    // 请求列表数据
    updateLoading(true);
    const newparams = {
      // UUID: searchValue,
      msgSourceId,
      effectiveStatus: +effectiveStatus
    };
    const { errCode, datas } = await quotaList(newparams);
    updateLoading(false);
    if (errCode === 0 && datas.length === 1) {
      const {
        msgSourceName,
        pushChannelName,
        ownerDeptName,
        owner,
        auditStatus,
        createTime,
        usedQuota,
        monthUsedQuota,
        renewQuota,
        monthRenewQuota,
        smsQuota
      } = datas[0];
      // NOTE: 接口返回的空是null
      const {
        quotaType, // 配额类型
        quotaPackageType,
        quota, // 配额 （单位：个）
        quotaPackageNum, // 配额包数量
        effectiveType, // 生效类型
        monitorMarginQuota, // 告警规则-短信配额剩余不足
        renewMarginQuota // 续订规则-短信配额剩余不足
      } = smsQuota || {};
      const initData = {
        msgSourceName,
        pushChannelName,
        ownerDeptName,
        owner,
        auditStatus,
        createTime,
        usedQuota,
        monthUsedQuota,
        renewQuota,
        monthRenewQuota,
        quotaType: quotaType || MONTH, // 无返回值，默认选中：按月份
        quotaPackageType: quotaPackageType || FIXED_PACKAGE, // 无返回值，默认选中：固定配额包
        quota,
        quotaPackageNum: quotaPackageNum || 1, // 无返回值，默认设置：1
        effectiveType: effectiveType || EFFECT_RIGHT_NOW, // 无返回值，默认选中：即刻生效
        monitorMarginQuota,
        renewMarginQuota,
        renewQuotaThousand: smsQuota.renewQuota / 1000 || undefined
      };
      // 数据
      updateCurData(initData);
      updateInitalData({ ...initData });
      // 触发onchange事件
      updateSyncQuotaType(initData.quotaType);
      updateSyncPackageType(initData.quotaPackageType);
      // 表单值回填

      if (initData.quotaPackageType === FIXED_PACKAGE) {
        setFieldsValue({
          quotaType: initData.quotaType,
          quotaPackageNum: initData.quotaPackageNum
        });
        // 回填配额包
        updateQuotaValue(initData.quota);
      } else {
        setFieldsValue({
          quotaThousand: initData.quota / 1000,
          quotaType: initData.quotaType
        });
      }

      // 统一的表单回填
      setFieldsValue({
        quotaPackageType: initData.quotaPackageType,
        effectiveType: initData.effectiveType,
        monitorMarginQuota: initData.monitorMarginQuota,
        renewMarginQuota: initData.renewMarginQuota,
        renewQuotaThousand: initData.renewQuotaThousand
      });
    } else {
      updateCurData({});
    }
  };

  // 初始化
  useEffect(() => {
    fetchList();
  }, [msgSourceId]);

  // 监听 配额包类型 值变化后
  useEffect(() => {
    if (
      syncPackageType === FIXED_PACKAGE &&
      !getFieldValue("quotaPackageNum")
    ) {
      setFieldsValue({
        quotaPackageNum: 1
      });
    }
  }, [syncPackageType]);

  const goBack = () => {
    history.replace(`/messageCenter/SMSmanagement/SMSquotaList`);
  };

  const onSubmit = e => {
    e.preventDefault();
    validateFieldsAndScroll(async (err, values) => {
      if (!err) {
        // eslint-disable-next-line camelcase
        const {
          quotaType,
          quotaPackageNum,
          quotaPackageType,
          quotaThousand,
          effectiveType,
          monitorMarginQuota,
          renewMarginQuota,
          renewQuotaThousand
        } = values;
        let params = {
          msgSourceId,
          quotaPackageType,
          quotaType,
          effectiveType,
          monitorMarginQuota,
          renewMarginQuota,
          renewQuota: floatThousandUnitValue(renewQuotaThousand)
        };

        if (quotaPackageType === FIXED_PACKAGE && !quotaValue) {
          message.error("请选择配额包");
          return;
        }

        if (quotaPackageType === FIXED_PACKAGE) {
          params = {
            ...params,
            quota: quotaValue,
            quotaPackageNum
          };
        } else {
          params = {
            ...params,
            quota: floatThousandUnitValue(quotaThousand)
          };
        }
        updateLoading(true);
        const { errCode, errMsg } = await addQuota(params);
        updateLoading(false);
        if (errCode === 0) {
          message.success("配置成功");
          goBack();
        } else {
          message.error(errMsg || "配置失败");
        }
      }
    });
    return true;
  };

  const renderButton = ({ controlDataProperty = [] }) => {
    const isAllDisabled = controlDataProperty.every(
      item => disabledFields[item] === true
    );

    const editCur = () => {
      const newDisabledStatus = { ...disabledFields };
      controlDataProperty.forEach(item => {
        newDisabledStatus[item] = false;
      });
      updateDisabledFields(newDisabledStatus);
    };

    const saveCur = () => {
      const newDisabledStatus = { ...disabledFields };
      controlDataProperty.forEach(item => {
        newDisabledStatus[item] = true;
      });
      updateDisabledFields(newDisabledStatus);
      return true;
    };

    // 还原表单值为之前的值
    const cancelCur = () => {
      const newDisabledStatus = { ...disabledFields };
      controlDataProperty.forEach(item => {
        setFieldsValue({
          [item]: initialData[item]
        });
        newDisabledStatus[item] = true;
        updateDisabledFields(newDisabledStatus);
        return true;
      });
    };

    return (
      <span>
        {isAllDisabled ? (
          <a onClick={editCur}>编辑</a>
        ) : (
          <React.Fragment>
            <a onClick={saveCur}>保存</a>
            <a onClick={cancelCur} style={{ marginLeft: 18 }}>
              取消
            </a>
          </React.Fragment>
        )}
      </span>
    );
  };

  const renderFixedPackage = () => (
    <React.Fragment>
      <Form.Item label="配额类型">
        {getFieldDecorator("quotaType", {
          rules: [
            {
              required: true,
              message: "请选择配额类型"
            }
          ]
        })(
          <Radio.Group
            onChange={e => {
              updateSyncQuotaType(e.target.value);
              updateQuotaValue();
            }}
          >
            <Radio value={MONTH}>按月份</Radio>
            <Radio value={YEAR}>按年份</Radio>
          </Radio.Group>
        )}
      </Form.Item>
      <Row style={{ marginBottom: 6 }}>
        <Col span={20} push={3}>
          <SMSpackageList
            type={syncQuotaType}
            onClick={updateQuotaValue}
            value={quotaValue}
            YEAR={YEAR}
            MONTH={MONTH}
          />
        </Col>
      </Row>
      <Form.Item label="配额包数量" required>
        <Row>
          <Col span={7}>
            {getFieldDecorator("quotaPackageNum", {
              rules: [
                {
                  required: true,
                  message: "请输入配额包数量"
                }
              ]
            })(<MinusInputAdd min={1} max={10} />)}
          </Col>
        </Row>
      </Form.Item>
    </React.Fragment>
  );

  const renderCustomPackage = () => (
    <React.Fragment>
      <Form.Item label="配额类型" required>
        <Col span={12}>
          {getFieldDecorator("quotaType", {
            rules: [
              {
                required: true,
                message: "请选择配额类型"
              }
            ]
          })(
            <Select
              placeholder="请选择"
              onChange={value => {
                updateSyncQuotaType(value);
              }}
            >
              <Select.Option value={MONTH}>按月份</Select.Option>
              <Select.Option value={YEAR}>按年份</Select.Option>
            </Select>
          )}
        </Col>
      </Form.Item>

      <Form.Item label="自定义条数" required>
        <Row>
          <Col span={12}>
            {getFieldDecorator("quotaThousand", {
              rules: [
                {
                  required: true,
                  message: "请输入条数（范围1~10000）"
                },
                {
                  min: 1,
                  type: "number",
                  message: "最小1"
                },
                {
                  max: 10000,
                  type: "number",
                  message: "最大10000"
                }
              ]
            })(
              <InputNumber
                placeholder="请输入条数（范围1~10000）"
                min={1}
                max={10000}
                precision={3}
                style={{ width: "100%" }}
              />
            )}
          </Col>
          <Col span={12}>
            <span style={{ marginLeft: 8 }}>千条</span>
          </Col>
        </Row>
      </Form.Item>
    </React.Fragment>
  );

  return (
    <FixedBottomWrapper
      className={styles.root}
      footer={
        <React.Fragment>
          <Button
            type="primary"
            onClick={onSubmit}
            style={{ marginLeft: 20, marginRight: 8 }}
          >
            确定
          </Button>
          <Button
            onClick={() => {
              goBack();
            }}
          >
            取消
          </Button>
        </React.Fragment>
      }
    >
      <Spin spinning={loading}>
        <div className={styles.content}>
          <div className={styles.title}>基本信息</div>
          <div className={styles.detail}>
            {rows.map((cols, index1) => (
              <Row key={index1}>
                {cols.map(({ title, dataKey, func }, index2) => {
                  const cur = curData[dataKey];
                  let renderString = "-";
                  if (func) {
                    renderString = func(cur);
                  } else if (cur || cur === 0) {
                    renderString = cur;
                  }
                  return (
                    <Col key={index2} span={12} className={styles.detailItem}>
                      <Col span={4}>{title}</Col>
                      <Col span={20} className={styles.detailItem_value}>
                        {renderString}
                      </Col>
                    </Col>
                  );
                })}
              </Row>
            ))}
          </div>
          <div
            className={styles.title_with_bottom_border}
            style={{
              marginTop: 16
            }}
          >
            配额规则
          </div>

          <Form {...formDefaultLayout} style={{ marginTop: 16 }}>
            <Form.Item label="配额包类型" required>
              {getFieldDecorator("quotaPackageType", {
                rules: [
                  {
                    required: true,
                    message: "请选择配额包类型"
                  }
                ]
              })(
                <Radio.Group
                  onChange={e => {
                    updateSyncPackageType(e.target.value);
                  }}
                >
                  <Radio.Button value={FIXED_PACKAGE}>固定配额包</Radio.Button>
                  <Radio.Button value={CUSTOM_PACKAGE}>
                    自定义配额包
                  </Radio.Button>
                </Radio.Group>
              )}
            </Form.Item>
            {syncPackageType === FIXED_PACKAGE && renderFixedPackage()}
            {syncPackageType === CUSTOM_PACKAGE && renderCustomPackage()}
            <Form.Item label="生效时间">
              {getFieldDecorator("effectiveType", {
                rules: [
                  {
                    required: true,
                    message: "请选择生效时间"
                  }
                ]
              })(
                <Radio.Group>
                  <Radio value={EFFECT_RIGHT_NOW}>即刻生效</Radio>
                  <Radio value={EFFECT_NEXT_TIME}>{`次${
                    syncQuotaType === MONTH ? "月" : "年"
                  }生效`}</Radio>
                </Radio.Group>
              )}
            </Form.Item>
            <div className={styles.title}>告警规则</div>
            <Form.Item label="短信配额剩余不足" labelCol={{ span: 3 }}>
              <Row>
                <Col span={12}>
                  {getFieldDecorator("monitorMarginQuota", {
                    rules: [
                      {
                        min: 1,
                        type: "number",
                        message: "最小1"
                      },
                      {
                        max: 10000000,
                        type: "number",
                        message: "最大1千万"
                      }
                    ]
                  })(
                    <InputNumber
                      style={{ width: "100%" }}
                      placeholder="请输入"
                      disabled={disabledFields.monitorMarginQuota}
                      min={1}
                      max={10000000}
                      precision={0}
                    />
                  )}
                </Col>
                <Col span={6}>
                  <span style={{ marginLeft: 8 }}>条时发出告警</span>
                </Col>
                <Col span={6}>
                  {renderButton({
                    controlDataProperty: ["monitorMarginQuota"]
                  })}
                </Col>
              </Row>
            </Form.Item>

            <div className={styles.title}>续订规则</div>
            {/* <Form.Item label="短信配额剩余不足" labelCol={{ span: 3 }}> */}
            <Row>
              <Col
                span={4}
                pull={1}
                style={{
                  color: "rgba(0, 0, 0, 0.85)",
                  textAlign: "right",
                  lineHeight: "40px",
                  marginLeft: 5
                }}
              >
                短信配额剩余不足：
              </Col>
              <Col span={15} pull={1}>
                <Col span={6}>
                  <Form.Item wrapperCol={{ span: 23 }}>
                    {getFieldDecorator("renewMarginQuota", {
                      rules: [
                        {
                          min: 1,
                          type: "number",
                          message: "最小1"
                        },
                        {
                          max: 10000000,
                          type: "number",
                          message: "最大1千万"
                        }
                      ]
                    })(
                      <InputNumber
                        style={{ width: "100%" }}
                        placeholder="请输入"
                        disabled={disabledFields.renewMarginQuota}
                        min={1}
                        max={10000000}
                        precision={0}
                      />
                    )}
                  </Form.Item>
                </Col>
                <Col
                  span={4}
                  style={{ textAlign: "center", lineHeight: "40px" }}
                >
                  条时自动续订
                </Col>
                <Col span={6}>
                  <Form.Item wrapperCol={{ span: 23 }}>
                    {getFieldDecorator("renewQuotaThousand", {
                      rules: [
                        {
                          min: 1,
                          type: "number",
                          message: "最小1"
                        },
                        {
                          max: 10000,
                          type: "number",
                          message: "最大10000"
                        }
                      ]
                    })(
                      <InputNumber
                        style={{ width: "100%" }}
                        placeholder="请输入"
                        disabled={disabledFields.renewQuotaThousand}
                        min={1}
                        max={10000}
                        precision={3}
                      />
                    )}
                  </Form.Item>
                </Col>
                <Col span={2} style={{ marginLeft: 8, lineHeight: "40px" }}>
                  千条
                </Col>
                <Col span={4} push={1} style={{ lineHeight: "40px" }}>
                  {renderButton({
                    controlDataProperty: [
                      "renewMarginQuota",
                      "renewQuotaThousand"
                    ]
                  })}
                </Col>
              </Col>
            </Row>
            {/* </Form.Item> */}
          </Form>
        </div>
      </Spin>
    </FixedBottomWrapper>
  );
}

export default Form.create()(Add);
